import cv2
import numpy as np


class Color_recognition:
    def __init__(self) -> None:
        self._dict_hand_landmarks = {}
        self.image = {}
        self.image_color = {}
        self.k = 20

    def set_frame(self, image, hand_landmarks):
        image_color = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        # image_color = image
        self._dict_hand_landmarks = hand_landmarks
        self.image = image
        self.image_color = image_color

    def get_frame(self):
        return self.image

    def main(self):
        arm_name = "Right"
        if arm_name in self._dict_hand_landmarks:
            list_arm = self._dict_hand_landmarks[arm_name]
            x0 = list_arm[0][0]
            y0 = list_arm[0][1]
            x5 = list_arm[5][0]
            y5 = list_arm[5][1]
            x17 = list_arm[17][0]
            y17 = list_arm[17][1]
            x12 = list_arm[12][0]
            y12 = list_arm[12][1]
            x4 = list_arm[4][0]
            y4 = list_arm[4][1]
            x20 = list_arm[20][0]
            y20 = list_arm[20][1]
            data = self.image_color[y5:y0, x5:x17]
            list_color = data.mean(axis=0).mean(axis=0)
            hsv_min = np.array(
                (
                    int(list_color[0] - self.k),
                    int(list_color[1] - self.k),
                    int(list_color[2] - self.k),
                ),
                np.uint8,
            )
            hsv_max = np.array(
                (
                    int(list_color[0] + self.k),
                    int(list_color[1] + self.k),
                    int(list_color[2] + self.k),
                ),
                np.uint8,
            )
            mask = cv2.inRange(self.image_color, hsv_min, hsv_max)
            y_k = int(abs(y12 - y0) / 10)
            x_k = int(abs(x4 - x20) / 10)
            mask = mask[y12 - y_k : y0 + y_k, x4 - x_k : x20 + x_k]
            contours, hierarchy = cv2.findContours(
                mask.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
            )
            cv2.drawContours(
                mask, contours, 5, (255, 0, 0), 10, cv2.LINE_AA, hierarchy, 1
            )
            cv2.imwrite("flip.png", mask)
            # return hsv_min,hsv_max
        else:
            return [-1.0, -1.0, -1.0], [-1.0, -1.0, -1.0]
